package com.example.newsclient.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.newsclient.R;
import com.example.newsclient.adapter.MyRecyclerAdapter;
import com.example.newsclient.bean.Top;
import com.example.newsclient.tool.API;
import com.example.newsclient.tool.NetUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 新闻资讯界面
 */
public class NewsFragment extends Fragment {

    private RecyclerView recyclerView;
    private NetUtil netUtil = NetUtil.getInstance();
    private List<Bitmap> imgUrlList;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    final List<Top.ResultBean.DataBean> dataBeanList = (List<Top.ResultBean.DataBean>) msg.obj;
                    //获取图片资源
                    imgUrlList = new ArrayList<>();
                    for(Top.ResultBean.DataBean dataBean : dataBeanList){
                        final String imgUrl = dataBean.getThumbnail_pic_s();
                        netUtil.getDataAsynFromNet(imgUrl, new NetUtil.MyNetCall() {
                            @Override
                            public void success(Call call, Response response) throws IOException {
                                InputStream inputStream = response.body().byteStream();
                                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                imgUrlList.add(bitmap);
                                if(imgUrlList.size() == dataBeanList.size()){
                                    //图片获取完成，更新列表
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            MyRecyclerAdapter adapter = new MyRecyclerAdapter(dataBeanList,imgUrlList,getContext());
                                            recyclerView.setAdapter(adapter);
                                            //设置布局管理器
                                            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                                        }
                                    });
                                }
                            }

                            @Override
                            public void failed(Call call, IOException e) {

                            }
                        });
                    }
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        initView(view);

        //网络请求数据
        getNewsData();
        return view;
    }

    /**
     * 初始化控件
     * @param view
     */
    private void initView(View view) {
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    }

    /**
     * 联网获取新闻数据(聚合平台提供)
     */
    public void getNewsData() {
        String url = API.API_NEWS;
        netUtil.getDataAsynFromNet(url, new NetUtil.MyNetCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                final String json = response.body().string();
                //解析json数据
                Gson gson = new Gson();
                Top top = gson.fromJson(json, Top.class);
                if(top.getError_code() == 0){//成功返回数据
                    //封装数据
                    List<Top.ResultBean.DataBean> dataBeanList = top.getResult().getData();
                    //提醒UI线程更新UI
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = dataBeanList;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                Log.e("NewsFragment","服务器异常");
            }
        });
    }
}
